package com.ctg.behavior.client.impala.factory;

import java.sql.Connection;
import java.sql.DriverManager;

import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.ctg.behavior.client.impala.config.CtImpalaConfig;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class CtImpalaFactory extends BasePooledObjectFactory<Connection> {

	@Autowired
	private CtImpalaConfig impalaConfig;
	
	@Override
	public Connection create() throws Exception {
		// 显示连接的服务器
		log.info("impalaConfig={}", JSON.toJSONString(impalaConfig));
        Class.forName(impalaConfig.getJdbcDriver());
		Connection connection = DriverManager.getConnection(impalaConfig.getConnectionUrl());
		return connection;
	}

	@Override
	public PooledObject<Connection> wrap(Connection hbaseConnection) {
		return new DefaultPooledObject<Connection>(hbaseConnection);
	}

	/**
	 * 销毁对象
	 */
	@Override
	public void destroyObject(PooledObject<Connection> p) throws Exception {
		Connection hbaseConnection = p.getObject();
		hbaseConnection.close();
		super.destroyObject(p);
	}

	@Override
	public boolean validateObject(PooledObject<Connection> p) {
		Connection ftpClient = p.getObject();
		boolean flag;
		try {
			flag = !ftpClient.isClosed();
			log.info("activeObject result: {}", flag);
			return flag;
		} catch (Exception e) {
			log.error("activeObject error");
			return false;
		}
	}

}
